//this would be part of a '.C' file such as 'Vec.C':
int Vec<T>::check(int i)
{
if (i < 0 || i >= xlen) throw BoundsViol("Vec", i, xlen);
return i;
}
Just as with 'swap()' above, repeating the above over and over for Vec of float, char, String, Vec, Vec-of-Vec-of-Vec, etc, will become tedious. Hence we create a single class template:
//this would go into a header file such as 'Vec.h':
template<class T>
class Vec {
int xlen;
T* xdata;
int check(int i); //return i if i>=0 && i<xlen else throw exception
//this would be part of a '.C' file such as 'Vec.C':
template<class T>
int Vec<T>::check(int i)
{
if (i < 0 || i >= xlen) throw BoundsViol("Vec", i, xlen);
return i;
}
Unlike template functions, template classes (instantiations of class templates) need to be explicit about the parameters over which they are instantiating:
main()
{
Vec<int> vi;
Vec<float> vf;
Vec<char*> vc;
Vec<String> vs;
Vec< Vec<int> > vv;
} // ^^^-- note the space; do NOT use Vec<Vec<int>> since the
// 'maximal munch' rule would grab a single '>>' token